package ch08_Swing高级组件.tree;

import ch07_GUI编程.BaseFrame;
import ch07_GUI编程.ImageFactory;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Enumeration;

public class JTreeDemo {
	public static void main(String[] args) throws IOException{
		BaseFrame f = new BaseFrame("JTree Demo");

		JTreeDemo demo = new JTreeDemo();
		DefaultMutableTreeNode root = demo.createNodesFromFile();
		JTree tree = new JTree(root);
		tree.setCellRenderer(new HardwareTreeCellRenderer());
		JScrollPane sp = new JScrollPane(tree);

		sp.setLocation(10, 10);
		sp.setSize(180, 200);
		f.add(sp);
		f.showMe();
	}
	DefaultMutableTreeNode createNodesFromFile() throws IOException{
		Hardware rootHw = new Hardware();
		rootHw.setId("00");
		rootHw.setName("硬件");
		rootHw.setIcon(ImageFactory.create("hardware.png"));

		DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootHw);

		URL url = getClass().getResource("data.txt");
		InputStreamReader in = new InputStreamReader(url.openStream());
		BufferedReader reader = new BufferedReader(in);
		String line;
		while((line = reader.readLine())!=null) {
			if(line.trim().length()<1) {
				continue;
			}
			Hardware h = new Hardware();
			String id = this.getId(line);
			String name = this.getName(line);
			h.setId(id);
			h.setName(name);

			if("0001".equals(id)) {
				h.setIcon(ImageFactory.create("cpu.png"));
			}else if ("0002".equals(id)) {
				h.setIcon(ImageFactory.create("ram.png"));
			}else if ("0003".equals(id)){
				h.setIcon(ImageFactory.create("gpu.png"));
			}else if ("0004".equals(id)) {
				h.setIcon(ImageFactory.create("hardDisk.png"));
			}
			DefaultMutableTreeNode node = new DefaultMutableTreeNode(h);
			DefaultMutableTreeNode parent = this.findParent(root,node);
			parent.add(node);
		}
		reader.close();
		return root;

	}
	String getId(String line) {
		return line.substring(0,line.indexOf("=")).trim();
	}

	String getName(String line) {
		return line.substring(line.indexOf("=")+1).trim();
	}

	DefaultMutableTreeNode findParent(DefaultMutableTreeNode root,DefaultMutableTreeNode node){
		String nodeId = ((Hardware)node.getUserObject()).getId();
		Enumeration nodes = root.breadthFirstEnumeration();
		while(nodes.hasMoreElements()) {
			DefaultMutableTreeNode n = (DefaultMutableTreeNode) nodes.nextElement();
			Hardware hw = (Hardware) n.getUserObject();
			String id = hw.getId();
			if(id.length()+2 == nodeId.length()&&nodeId.startsWith(id)) {
				return n;
			}
		}
		return root;

	}
}
